package com.zdlog.wenjuan.service.impl;

import com.zdlog.wenjuan.VO.ResultBoolenVO;
import com.zdlog.wenjuan.VO.ResultVO;
import com.zdlog.wenjuan.dao.UserInfoRepository;
import com.zdlog.wenjuan.dataobject.UserInfo;
import com.zdlog.wenjuan.enums.ResultEnum;
import com.zdlog.wenjuan.service.UserService;
import com.zdlog.wenjuan.util.MD5Util;
import com.zdlog.wenjuan.util.ResultBoolenVOUtil;
import com.zdlog.wenjuan.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @program: wenjuanSer
 * @PACKAGE_NAME: com.zdlog.wenjuan.service.impl
 * @author: Kuaile
 * @create: 2018-02-03 23:42
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoRepository repository;

    @Override
    public ResultBoolenVO register(UserInfo userInfo) {
        UserInfo result = repository.findByUsername(userInfo.getUsername());
        if (result != null) {
            return ResultBoolenVOUtil.error(ResultEnum.USER_USERNAME_EXIST.getMessage());
        }
        String md5Password = MD5Util.MD5EncodeUtf8(userInfo.getPassword());
        userInfo.setPassword(md5Password);
        UserInfo result1 = repository.save(userInfo);
        if (result1 != null) {
            return ResultBoolenVOUtil.success();
        }else {
            return ResultBoolenVOUtil.error(ResultEnum.REGISTER_USER_ERROR.getMessage());
        }

    }



    @Override
    public ResultVO login(String username, String password) {
        UserInfo result = repository.findByUsername(username);
        if (result == null) {
            return ResultVOUtil.error(ResultEnum.USER_NOT_USERNAME.getCode(), ResultEnum.USER_NOT_USERNAME.getMessage());
        }
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        if (!result.getPassword().equalsIgnoreCase(md5Password)) {
            return ResultVOUtil.error(ResultEnum.USER_PASSWORD_ERROR.getCode(), ResultEnum.USER_PASSWORD_ERROR.getMessage());
        }

        return ResultVOUtil.success(result);
    }


    /**
     * 检车邮箱是否被注册，被注册返回trur，未注册返回flase
     *
     * @param email
     * @return
     */
    @Override
    public Boolean checkEmail(String email) {

        UserInfo userInfo = repository.findByEMail(email);
        if (userInfo != null)
            return true;

        return false;
    }


    /**
     * 检查用户名是否被注册，被注册返回trur，未注册返回flase
     * @param name
     * @return
     */
    @Override
    public Boolean checkName(String name) {
        UserInfo userInfo = repository.findByUsername(name);
        if (userInfo != null) {
            return true;
        }
        return false;
    }

    @Override
    public UserInfo findUserId(String userId) {
        return repository.findByUserId(userId);
    }

}

